﻿Shader "Anisotropy"
{
    Properties
    {
        _BaseColor("Color",Color) = (1,1,1,1)
        _BaseMap("Texture",2D) = "white"{}
        _Tangent ("Tangent", Range(0, 1)) = 0
        _Gloss("Gloss",Range(0.01,1)) = 0.25

    }
    SubShader
    {
        Tags
        {
            "RenderPipeline"="UniversalRenderPipeline"
            "LightMode"="UniversalForward"
            "RenderType"="Opaque"
        }
        LOD 100

        HLSLINCLUDE
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"        //类似UnityCG.iginc
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"    //光照hlsl


        TEXTURE2D(_BaseMap);    SAMPLER(sampler_BaseMap);

        CBUFFER_START(UnityPerMaterial)
        float4 _BaseMap_ST;
        half4 _BaseColor;
        half _Gloss;
        half _Tangent;

        CBUFFER_END
        ENDHLSL
        
        pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            
            struct a2v
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
                float3 tangentOS : TANGENT;
                float2 texcoord : TEXCOORD;
            };
            
            struct v2f
            {
                float4 positionCS : SV_POSITION;
                half3 positionWS : TEXCOORD0;
                half3 normalWS : NORMAL;
                half3 binormalWS : TEXCOORD1;
                half2 texcoord : TEXCOORD2;
            };
            
            v2f vert(a2v v)
            {
                v2f o;
                o.positionCS = TransformObjectToHClip(v.positionOS.xyz);
                o.positionWS = TransformObjectToWorld(v.positionOS.xyz);
                o.normalWS = TransformObjectToWorldNormal(v.normalOS.xyz);
                
                half3 tangentWS = TransformObjectToWorldDir(v.tangentOS.xyz);
                o.binormalWS = cross(tangentWS, o.normalWS);
                o.texcoord = TRANSFORM_TEX(v.texcoord,_BaseMap);
                return o;
            }

            half4 frag(v2f i):SV_Target
            {
                Light light = GetMainLight();
                half3 normalWS = normalize(i.normalWS);
                half3 viewDir = normalize(GetCameraPositionWS() - i.positionWS);
                half3 halfDir = normalize(light.direction + viewDir);
                half3 AReflectDirection = normalize(light.direction + viewDir);
                half3 ANormalWS = normalize(lerp(normalWS + i.binormalWS, i.binormalWS, _Tangent));
                float Anisotropic = dot(ANormalWS, AReflectDirection);
                half specular = pow(saturate(sqrt(1- (Anisotropic* Anisotropic))), _Gloss* 128);
                return specular;
            }
            ENDHLSL
        }
    }
}